#include "kernel.h"

struct screen * const screen_pointer = (struct screen*) 0xB8000;

int curr_row = 0;
int curr_col = 0;

/*! Clears the screen. */
void clear_screen(void) {
	register int row, column;

	for (row = 0; row < MAX_ROWS; row++) {
		for (column = 0; column < MAX_COLS; column++) {
			screen_pointer->positions[row][column].character = ' ';
		}
	}
}

/* Modify these function in databar assignment 6. */

void
kprints(const char* string) {
	kprintat(curr_row, curr_col, string);	// mutate the current cursor position
}

void
kprinthex(const register long value) {
	const static char hex_helper[16] = "0123456789abcdef";
	register int i;

	char tmp[17] = {0};
	
	/* Print each character of the hexadecimal number. This is a very inefficient
	   way of printing hexadecimal numbers. It is, however, very compact in terms
	   of the number of source code lines. */
	for (i = 15; i >= 0; i--) {
//		outb(0xe9, hex_helper[(value >> (i * 4))&15]);
		tmp[15-i] = hex_helper[(value >> (i * 4))&15];
	}
	
	kprints(tmp);
}

int kprintat(int row, int col, char *str) {
	int ret = 1;
	
	curr_row = row;
	curr_col = col;
	
	for (; *str; str++) {
		if (*str == '\n') { // go to next line
			curr_row++;
			curr_col = 0;
			continue;
		}

		if (curr_col >= 80) { // go to next line
			curr_row++;
			curr_col = 0;
		}
		
		if (curr_row >= 25) {
			ret = 0; // we fail if we need to scroll
			break;
		} else {
			screen_pointer->positions[curr_row][curr_col].character = *str;
//			screen_pointer->positions[curr_row][curr_col].attribute = curr_row*16+curr_col;
			curr_col++;
		}
	}

	return ret;
}

